package com.zl.filter;

import com.zl.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author ljm
 */
public class UserIsLogin implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("用户是否登录过滤器创建....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("用户是否登录过滤器前");
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        HttpSession session=req.getSession();
        User loginUser= (User) session.getAttribute("loginUser");
        String path=req.getServletPath();//   /login.jsp

        //String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
        String basePath = "http://192.168.1.120:8050/empMaven/";

        System.out.println("当前拦截到的请求为:"+path);
        /**
         * /js/jquery-2.1.4.js
         */
        String[] okPath={"/css/","/js/","/user/regName","/reg.jsp","/login.jsp","/user/login","/user/regUser","/test","error.jsp","/restFul"};
        boolean flag=false;
        for(String ok:okPath){
            if(path.indexOf(ok)>=0){
                flag=true;
                break;
            }
        }
        if(flag||loginUser!=null){
            //登录过了
            filterChain.doFilter(req,resp);
        }else{
            //没有登录
            resp.sendRedirect(basePath + "login.jsp?error="+ URLEncoder.encode("非法请求,请先登录!!","utf-8"));
        }
        System.out.println("用户是否登录过滤器后");
    }

    @Override
    public void destroy() {
        System.out.println("用户是否登录过滤器销毁....");
    }

    public static void main(String[] args) {
        String ok="/js/5";
        String path="/js/jquery-2.1.4.js";
        System.out.println(path.indexOf(ok));
    }
}
